package com.feng.financial.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Administrator
 */
public class WebErrorController extends BasicErrorController {

    public static final Logger LOGGER = LoggerFactory.getLogger(WebErrorController.class);

    public WebErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);
        LOGGER.info(map.toString());
        ErrorCode errorCode = ErrorCode.getInstance((String) map.get("code"));
        map.put("statusCode",errorCode.getStatusCode());
        map.put("statusDesc",map.get("message"));
        badRequestMsg(map);// 如果是请求参数有误，返回错误参数信息
        map.remove("timestamp");
        map.remove("status");
        map.remove("error");
        map.remove("path");
        map.remove("errors");
        return map;
    }

    /**
     * 如果是请求参数有误，返回错误参数信息
     * @param map
     */
    private void badRequestMsg(Map<String, Object> map) {
        ArrayList<MethodArgumentNotValidVo> errorArgs = new ArrayList<>();
        if (Objects.equals(map.get("status"), HttpStatus.BAD_REQUEST.value())) {
            try {
                Collection errors = (Collection) map.get("errors");
                if (errors == null) return;
                for (Object error : errors) {
                    ObjectError oe = (ObjectError) error;
                    errorArgs.add(
                            new MethodArgumentNotValidVo(oe.getObjectName(),oe.getDefaultMessage(),Arrays.toString(oe.getCodes()))
                    );
                }
            } catch (Exception e) {
                LOGGER.error("错误请求参数 : " + e.getMessage());
            }
            map.put("errorArgs",errorArgs);
            map.put("statusCode",ErrorCode.PARAM_ERROR.getStatusCode());
            map.put("statusDesc",ErrorCode.PARAM_ERROR.getStatusDesc());
        }
    }

}
